using System.Collections.Concurrent;
using System.Net.Sockets;

namespace SimpleSocket
{
    internal class SocketAsyncEventArgsPool
    {
        private readonly int _poolSize;
        private readonly int _messageBufferSize;
        private readonly ConcurrentQueue<SocketAsyncEventArgs> _pool = new ConcurrentQueue<SocketAsyncEventArgs>();

        public SocketAsyncEventArgsPool(int messageBufferSize, int poolSize = 10000)
        {
            _messageBufferSize = messageBufferSize;
            _poolSize = poolSize;
        }
        
        
        public SocketAsyncEventArgs Acquire()
        {
            SocketAsyncEventArgs e;
            if (this._pool.TryDequeue(out e)) return e;

            e = new SocketAsyncEventArgs();
            e.SetBuffer(new byte[this._messageBufferSize], 0, this._messageBufferSize);
            return e;
        }
   
        public void Release(SocketAsyncEventArgs e)
        {
            if (this._pool.Count < 10000)
            {
                this._pool.Enqueue(e);
                return;
            }

            e.Dispose();
        }
    }
}